home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1424 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  91 lines

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: GoTo equivalent in C ??
  5. Date: 13 Jan 1996 18:05:58 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4d8sa6$mqc@news.iag.net>
  8. References: <4d67vm$e5h@masala.cc.uh.edu>
  9. NNTP-Posting-Host: pm2-orl20.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <4d67vm$e5h@masala.cc.uh.edu>, sukku@menudo.uh.edu says...
  13. >
  14. >Hi,
  15. >        I have always thought about this. How do you get the effect of goto
  16. >in C without using "goto"?? For ex, if I have to check for an error in my
  17. >function for every computation I do, and then do some cleaning up, how do 
  18. >I do it. Here is an example:
  19. >
  20. >f()
  21. >{
  22. >
  23. >char *s = (char *) malloc(10 * sizeof(char));
  24. >int i;
  25. >
  26. >i = scanf("%s", s);
  27. >
  28. >if(i != 1) /* I wish I could do a goto to the last two lines of the 
  29. function*/
  30. >{
  31. >        free(s); 
  32. >        return;
  33. >}
  34. >
  35. >i = atoi(s);
  36. >if(i==0)
  37. >{
  38. >        free(s);
  39. >        return;
  40. >
  41. >}
  42. >free(s);
  43. >return;
  44. >
  45. >}
  46.  
  47. f()
  48.    {
  49.    int i;
  50.    char *s = malloc(10 * sizeof(char));
  51.  
  52.    if( s != NULL)                /* allocation succeeeded */
  53.       {
  54.       if( (scanf("%s", s)) == 1) /* 1 field input */
  55.          {
  56.          if( (i = atoi(s)) != 0) /* converted to non-zero integer */
  57.             {
  58.             /* more code */
  59.             }
  60.          }
  61.       free(s);
  62.       }
  63.    return;
  64.    }
  65.  
  66. or
  67.  
  68. f()
  69.    {
  70.    int i;
  71.    char *s = malloc(10 * sizeof(char));
  72.  
  73.    if( s != NULL)                /* successful allocation */
  74.       {
  75.       if( ((scanf("%s", s)) == 1)) && ((i = atoi(s)) != 0) ) /* valid input */
  76.          {
  77.          /* more code */
  78.          }
  79.       free(s);
  80.       }
  81.    return;
  82.    }
  83.  
  84. Note: The && operator guarantees that the scanf test must succeed _before_
  85. the atoi can be called.
  86.  
  87. -- 
  88. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  89. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  90.  
  91.